﻿using System;
using System.Data.SqlServerCe;

namespace SS.Common.DBBuilder.DBInteraction
{
    /// <summary>
    /// The class implement AbstractDataProvider is used to provide the means to get data from database SQLServerCE
    /// </summary>
    public class SQLServerCEDataProvider: AbstractDataProvider
    {
        #region Ctors

        /// <summary>
        /// Initialize instance of SQLServerCEDataProvider based on data source and database name
        /// </summary>
        /// <param name="dataSource">DataSource</param>
        public SQLServerCEDataProvider(string dataSource)
        {
            Logger.Info("Init SQLServerCEDataProvider --> Start");

            this.DataSource = string.Format("Data Source={0};", dataSource);

            Logger.InfoFormat("Connection String: {0}", this.DataSource);
            
            this.ObjConnection = new SqlCeConnection(this.DataSource);

            Logger.Info("Init SQLServerCEDataProvider <-- End");
        }

        #endregion

        #region Help methods

        /// <summary>
        /// Initialize sql command
        /// </summary>
        protected override void InitializeCommand()
        {
            if (ObjCommand == null)
            {
                try
                {
                    Logger.Info("InitializeCommand --> Start");
                    Logger.InfoFormat("Query: {0}", Query);

                    this.ObjCommand = new SqlCeCommand(Query, (SqlCeConnection)ObjConnection);

                    Logger.Info("InitializeCommand <-- End");
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("InitializeCommand: {0}", ex.ToString());
                    throw new Exception(ex.ToString());
                }
            }
        }

        /// <summary>
        /// Initialize a set of command
        /// </summary>
        protected override void InitializeDataAdapter()
        {
            try
            {
                Logger.Info("InitializeDataAdapter --> Start");

                this.ObjDataAdapter = new SqlCeDataAdapter
                {
                    SelectCommand = (SqlCeCommand)ObjCommand
                };

                Logger.Info("InitializeDataAdapter <-- End");
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("InitializeDataAdapter: {0}", ex.ToString());
                throw new Exception(ex.ToString());
            }
        }

        #endregion
    }
}
